<template>
    <PopList :title="'CesiumLab4'" :link="'http://bjxbsj.cn'" :showButton="true" @close="close" @ok="addSceneObjects">
        <div class="images_bottom_content">
            <div class="images_servelocation">
                <label>服务地址</label><input type="text" v-model="serverUrl" @blur="initNewList"
                    @keydown.enter="initNewList">
            </div>
            <div class="images_servelocation">
                <label>查询内容</label><input type="text" v-model="searchValue" @blur="searchTargetList"
                    @keydown.enter="searchTargetList">
            </div>
            <!-- <div class="images_servelocation" v-if="informationShow">
                <label>服务地址</label><input type="text" v-model="serveUrl">
            </div> -->
            <div class="images_servelocation" v-if="informationShow">
                <label>瓦片url</label>
                <div class="images_servelocation_readonly">{{ serveUrl }}</div>
            </div>
            <div class="images_lab_list">
                <div class="images_lab_son" v-for="(item, index) in newlist">
                    <label for="">{{ item[0].createTime.substring(0, 10) }}</label>
                    <div class="images_lab_son_list">
                        <div v-for="(i, ind) in item" class="images_img_lilist">
                            <div class="images_imgposition" @click="changeInformation(i, index, ind)"
                                :class="{ 'images_checkedactive': checkedactive == index && checkedInd == ind }">
                                <span v-show="iconIsShow === index && iconIndIsShow === ind ? true : false">{{ i.name
                                    }}</span>
                                <img :src="i.thumbnail ?? emptyImg" alt="">
                            </div>
                            <div class="images_onlineimageName" @mouseenter="handleMouseEnter(index, ind)"
                                @mouseleave="handleMouseLeave">
                                {{ i.name }}
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </PopList>
</template>

<script setup lang="ts">
import { Message } from "earthsdk-ui";
import { ES3DTileset } from "esobjs-xe2-plugin/dist-node/esobjs-xe2-plugin-main";
import { inject, onMounted, ref, watch ,onBeforeUnmount} from 'vue';
import { SceneTree } from 'xbsj-xe2/dist-node/xe2';
import { get } from '../../../api/service';
import PopList from "../../../components/PopList.vue";
import { XbsjEarthUi } from "../../../scripts/xbsjEarthUi";
import { createVueDisposer, toVR } from 'vue-xe2-plugin/dist-node/components/xe2/tools';

const xbsjEarthUi = inject('xbsjEarthUi') as XbsjEarthUi
const sceneTree = inject('sceneTree') as SceneTree
const serveUrl = ref('')
const checkedactive = ref()
const searchValue = ref('')
const informationShow = ref(false)
const itemName = ref('')
const iconIsShow = ref()
const lablist = ref()
const newlist = ref()
const iconIndIsShow = ref()
const checkedInd = ref()
const serverUrl = ref()
const d = createVueDisposer(onBeforeUnmount)

const cesiumLabToken = toVR<string>(d, [xbsjEarthUi, 'cesiumLabToken'])

const emptyImg = require('../../../assets/common/model.png')
const emits = defineEmits(['close', 'add']);
const close = () => {
    emits("close")
}
const addSceneObjects = () => {
    if (!serveUrl.value) Message.warning('请选择或者输入地址');
    else if (serveUrl.value) {

        const currentTreeItem = sceneTree.lastSelectedItem
        let newTreeItem
        if (!currentTreeItem) {
            newTreeItem = sceneTree.createSceneObjectTreeItem('ES3DTileset')
        } else if (currentTreeItem?.type === 'Folder') {
            newTreeItem = sceneTree.createSceneObjectTreeItem('ES3DTileset', undefined, currentTreeItem, 'Inner')
        } else {
            newTreeItem = sceneTree.createSceneObjectTreeItem('ES3DTileset', undefined, currentTreeItem, 'After')
        }
        if (!newTreeItem) return
        sceneTree.uiTree.clearAllSelectedItems()
        newTreeItem.uiTreeObject.selected = true
        if (!newTreeItem.sceneObject) return
        if (newTreeItem.sceneObject.typeName !== 'ES3DTileset') return
        const sceneObject = newTreeItem.sceneObject as ES3DTileset
        xbsjEarthUi.propSceneTree = newTreeItem
        newTreeItem.name = itemName.value
        sceneObject.url = serveUrl.value
        emits("close")
    }
}
type ListDataItem = {
    "id": string,
    "name": string,
    "description": null,
    "storageType": string,
    "storageUri": string,
    "thumbnail": null,
    "userId": null,
    "version": string,
    "subDomain": null,
    "createTime": string,
    "updateTime": null,
    "cors": null,
    "tilesetJson": null,
    "zip": null
}
const groupBy = (array: ListDataItem[], f: Function) => {
    const groups: {
        [key: string]: ListDataItem[],
    } = {};
    array.forEach((item) => {
        const group = JSON.stringify(f(item));
        groups[group] = groups[group] || [];
        groups[group].push(item);
    });
    return Object.keys(groups).map((group) => {
        return groups[group];
    });
};
const sortClass = (sortData: ListDataItem[]) => {
    const sorted = groupBy(sortData, (item: ListDataItem) => {
        return item.createTime.substring(0, 10);
    });
    return sorted.reverse();
};
const handleMouseEnter = (index: number, ind: number) => {
    iconIsShow.value = index
    iconIndIsShow.value = ind
}
const handleMouseLeave = () => {
    iconIsShow.value = null
    iconIndIsShow.value = null
}
const changeInformation = (item: any, index: number, ind: number) => {
    checkedactive.value = index
    checkedInd.value = ind
    informationShow.value = true
    serveUrl.value = (`${serverUrl.value}/tile/model/${item.id}/tileset.json`)+ `${cesiumLabToken.value ? '?labtoken=' + cesiumLabToken.value : ''}`
    itemName.value = item.name
}
const searchTargetList = () => {
    get(`${serverUrl.value}/tile/model/list?key=${searchValue.value}&sort=desc&order=createTime`).then((res: any) => {
        if (res && res.data) {
            lablist.value = res.data.list

                .value = sortClass(lablist.value)
        }
    }).catch(error => {
        console.log(error);
        Message.error('请求地址错误')
        newlist.value = []
    })
}
watch(serverUrl, (val) => {
    xbsjEarthUi.cesiumLabUrl = val
},)
const initNewList = () => {
    get(`${serverUrl.value}/tile/model/list?sort=desc&order=createTime&labtoken=${cesiumLabToken.value}`).then((res: any) => {
        if (res && res.data) {
            lablist.value = res.data.list
            newlist.value = sortClass(lablist.value)
        }
    }).catch(error => {
        console.log(error);
        Message.error('请求地址错误')
        newlist.value = []
    })
}
onMounted(() => {
    serverUrl.value = xbsjEarthUi.cesiumLabUrl
    initNewList()

})
</script>